package com.zhz.lib.cms.security.userinfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;

import com.zhz.lib.cms.domain.quanxian.User;
import com.zhz.project.common.util.hibernate.BaseDAO;

public class UserInfoBuilderImplWithJdbc implements UserInfoBuilder {

    private BaseDAO baseDao;

    private String  authorityUrl = "SELECT ga.authority "
                                   + "FROM Groups g, GroupMembers gm, GroupAuthorities ga "
                                   + "WHERE g.id = ga.groupId AND g.id = gm.groupId and gm.username='";

    @SuppressWarnings("unchecked")
    public Map<String, UserInfo> buildUserInfoMap(String username) {
        Map<String, UserInfo> userMap = new HashMap<String, UserInfo>();
        
        List<User> userinfolist = baseDao.find("User", "username", username);
        List list = baseDao.select(authorityUrl + username + "'");
        
        if (null != list){
            int size = list.size();
            if (size > 0) {
                User user = userinfolist.get(0);
                int status = user.getStatus();
                boolean enable = status == 1 ? true : false;
                String password = user.getPassword();
                Integer id = user.getId();
                String email = user.getEmail();
                String name = user.getName();
                String department = user.getDepartment();

                GrantedAuthority[] ga = new GrantedAuthority[list.size()];

                for (int k = 0; k < size; k++) {
                    String authority = list.get(k).toString();
                    ga[k] = new GrantedAuthorityImpl(authority);
                }
                UserInfo ui = new UserInfo(username, password, enable, ga);
                ui.setId(Integer.toString(id));
                ui.setEmail(email);
                ui.setName(name);
                ui.setDepartment(department);
                userMap.put(username, ui);
            }
        }
        return userMap;
    }

    public void setBaseDao(BaseDAO baseDao) {
        this.baseDao = baseDao;
    }

}
